package com.gitee.zhuyunlong2018.mybatisplusrelations.utils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class CollectionUtils {

    /**
     * 将一个集合进行分割
     *
     * @param collections 需要分割的集合 (List LinkedHashSet TreeSet LinkedList)
     * @param maxNum      集合最大的数量
     * @return 分割后的集合
     */
    public static <T> Collection<Collection<T>> subCollection(Collection<T> collections, long maxNum) {
        if (collections.getClass() == HashSet.class) {
            collections = new ArrayList<>(collections);
        }
        //计算切分次数
        long limit = (collections.size() + maxNum - 1) / maxNum;
        Collection<T> finalCollections = collections;
        return Stream.iterate(0, n -> n + 1)
                .limit(limit)
                .parallel()
                .map(
                        a -> {
                            System.out.println(a);
                            return finalCollections
                                    .stream()
                                    .skip(a * maxNum)
                                    .limit(maxNum)
                                    .parallel()
                                    .collect(Collectors.toList());
                        }
                ).collect(Collectors.toList());
    }
}
